package top.codestudy.wanandroid.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import androidx.appcompat.widget.AppCompatButton;

import top.codestudy.wanandroid.R;


public class RotateAnimationButton extends AppCompatButton {
    private String TAG = getClass().getSimpleName();

    //是否重置旋转
    private boolean isReset = false;

    public RotateAnimationButton(Context context) {
        this(context, null);
    }

    public RotateAnimationButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RotateAnimationButton(final Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackground(getResources().getDrawable(R.drawable.ic_home_black_24dp, null));
        Log.i(TAG, "RotateAnimationButton: ");
        setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Animation rotate = null;
                if (!isReset) {
                    rotate = AnimationUtils.loadAnimation(context, R.anim.rotate_anim);
                    isReset = true;
                } else {
                    rotate = AnimationUtils.loadAnimation(context, R.anim.roteate_rest_anim);
                    isReset = false;
                }
                final Animation finalRotate = rotate;
                rotate.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        if (isReset){
                            setBackground(getResources().getDrawable(R.drawable.ic_action_hot, null));
                        } else {
                            setBackground(getResources().getDrawable(R.drawable.ic_home_black_24dp, null));
                        }
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                rotate.setFillAfter(true);
                startAnimation(rotate);

            }
        });
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility){
        super.onWindowVisibilityChanged(visibility);
        Log.i(TAG, "onWindowVisibilityChanged: visibility ==> " + visibility);
    }

}
